<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="tenant_id" label="所属商户" required>
        <uni-data-select 
          v-if="isAdmin" 
          v-model="formData.tenant_id" 
          :localdata="tenantOptions" 
          @change="onTenantChange"
          placeholder="请选择商户">
        </uni-data-select>
        <uni-easyinput 
          v-else 
          v-model="formData.tenant_id" 
          disabled>
        </uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="category_id" label="所属分类" required>
        <uni-data-select
          v-model="formData.category_id"
          :localdata="categoryOptions"
          :placeholder="isAdmin && !formData.tenant_id ? '请先选择商户' : '请选择分类'"
          :disabled="isAdmin && !formData.tenant_id">
        </uni-data-select>
        <text v-if="isAdmin && !formData.tenant_id" style="color: #909399; font-size: 12px; margin-top: 5px;">
          请先选择商户，再选择分类
        </text>
      </uni-forms-item>
      <uni-forms-item name="name" label="菜品名称" required>
        <uni-easyinput placeholder="菜品名称" v-model="formData.name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="image" label="菜品图片">
        <uni-file-picker 
          v-model="formData.imageFiles" 
          fileMediatype="image" 
          mode="grid"
          :auto-upload="true"
          :upload-user-oid="true"
          :server-url="uploadConfig.serverUrl"
          :folder="uploadConfig.folder"
          @select="onImageSelect"
          @success="onUploadSuccess"
          @delete="onImageDelete"
          limit="1"
          :image-styles="imageStyles">
        </uni-file-picker>
        <text v-if="formData.image" style="font-size: 12px; color: #999; margin-top: 5px;">
          已上传图片路径: {{formData.image}}
        </text>
      </uni-forms-item>
      <uni-forms-item name="description" label="菜品描述">
        <uni-easyinput placeholder="菜品描述" v-model="formData.description" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="price" label="价格" required>
        <uni-easyinput type="number" placeholder="输入价格" v-model="formData.price">
          <template v-slot:right>
            <text style="color: #666;">元</text>
          </template>
        </uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="original_price" label="原价">
        <uni-easyinput type="number" placeholder="输入原价（可选）" v-model="formData.original_price">
          <template v-slot:right>
            <text style="color: #666;">元</text>
          </template>
        </uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="sort" label="排序值">
        <uni-easyinput placeholder="排序值（越小越靠前）" type="number" v-model="formData.sort"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="is_hot" label="热销标记">
        <switch @change="binddata('is_hot', $event.detail.value)" :checked="formData.is_hot"></switch>
      </uni-forms-item>
      <uni-forms-item name="is_new" label="新品标记">
        <switch @change="binddata('is_new', $event.detail.value)" :checked="formData.is_new"></switch>
      </uni-forms-item>
      <uni-forms-item name="status" label="状态">
        <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/food_items.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'food_items';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "tenant_id": "",
        "category_id": "",
        "name": "",
        "image": "",
        "description": "",
        "price": null,
        "original_price": null,
        "sort": 100,
        "is_hot": false,
        "is_new": false,
        "status": 1,
        "created_at": null,
        "updated_at": null,
        "imageFiles": []
      }
      return {
        formData,
        isAdmin: false,
        currentTenantId: '',
        tenantOptions: [],
        categoryOptions: [],
        allCategories: [],
        formOptions: {
          "status_localdata": [
            {
              "text": "下架",
              "value": 0
            },
            {
              "text": "上架",
              "value": 1
            }
          ],
          "is_hot_localdata": [
            {
              "text": "否",
              "value": 0
            },
            {
              "text": "是",
              "value": 1
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        },
        imageStyles: {
          width: 100,
          height: 100,
          border: {
            color: '#eee',
            width: 1,
            style: 'solid',
            radius: '5px'
          }
        },
        uploadConfig: {
          serverUrl: '',
          folder: 'food_images'
        },
        cloudProvider: 'alipay', // 'alipay'或'aliyun'
        imageUrlMap: {}  // 用于缓存云存储URL到HTTP URL的映射
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    mounted() {
      // 从Storage获取用户信息，而不是Vuex
      const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {}
      this.isAdmin = userInfo.isAdmin === true
      this.currentTenantId = userInfo.tenant_id || ''
      
      if (!this.isAdmin && this.currentTenantId) {
        this.formData.tenant_id = this.currentTenantId
        this.loadCategories()
      }
      
      if (this.isAdmin) {
        this.loadTenants()
      }

      if (this.formData.image && !this.formData.imageFiles.length) {
        // 如果有图片路径但没有预览数据，创建预览对象
        this.formData.imageFiles = [{
          name: '已上传图片',
          url: this.formData.image,
          type: 'image',
          progress: 100,
          status: 'success'
        }]
      }

      // 检测云环境
      this.detectCloudProvider();
    },
    methods: {
      async loadTenants() {
        try {
          const { result } = await uniCloud.callFunction({
            name: 'get-tenants',
            data: {}
          })
          
          if (result?.data) {
            this.tenantOptions = result.data.map(tenant => ({
              value: tenant.tenant_id,
              text: tenant.tenant_name || tenant.name || `商户(${tenant.tenant_id})`
            }))
          }
        } catch (e) {
          console.error('加载商户数据失败', e)
          uni.showToast({
            title: '加载商户列表失败',
            icon: 'none'
          })
        }
      },
      
      async loadCategories() {
        try {
          const tenantId = this.isAdmin ? this.formData.tenant_id : this.currentTenantId
          
          if (!tenantId) {
            this.categoryOptions = []
            return
          }
          
          let whereClause = {}
          whereClause = { tenant_id: tenantId }
          
          const { result } = await uniCloud.callFunction({
            name: 'get-categories',
            data: { where: whereClause }
          })
          
          if (result?.data) {
            this.allCategories = result.data
            
            this.categoryOptions = result.data.map(category => ({
              value: category._id,
              text: category.name || `未命名分类(${category._id})`
            }))
            
            if (this.categoryOptions.length === 0) {
              uni.showToast({
                title: '该商户暂无分类数据',
                icon: 'none'
              })
            }
          }
        } catch (e) {
          console.error('加载分类数据失败', e)
          uni.showToast({
            title: '加载分类列表失败',
            icon: 'none'
          })
        }
      },
      
      onTenantChange(value) {
        this.formData.category_id = ''
        this.categoryOptions = []
        
        if (value) {
          this.loadCategories()
        } else {
          uni.showToast({
            title: '请先选择商户',
            icon: 'none'
          })
        }
      },
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },
      submitForm(value) {
        // 自动设置创建时间和更新时间
        value.created_at = Date.now()
        value.updated_at = Date.now()
        
        if (!value.tenant_id && !this.isAdmin) {
          value.tenant_id = this.currentTenantId
        }
        
        // 如果有图片上传文件，但没有设置image字段，进行处理
        if (!value.image && this.formData.imageFiles.length > 0 && this.formData.imageFiles[0].url) {
          value.image = this.formData.imageFiles[0].url
        }
        
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },
      onImageSelect(e) {
        console.log('选择文件：', e)
      },
      onUploadSuccess(e) {
        console.log('上传成功：', e)
        // 将上传成功后的文件路径存入表单数据
        if (e.tempFilePaths && e.tempFilePaths.length > 0) {
          this.formData.image = e.tempFilePaths[0]
        } else if (e.tempFiles && e.tempFiles.length > 0 && e.tempFiles[0].url) {
          this.formData.image = e.tempFiles[0].url
          
          // 确保imageFiles有正确的数据结构用于预览
          if (!this.formData.imageFiles.length || !this.formData.imageFiles[0].url) {
            this.formData.imageFiles = [{
              name: e.tempFiles[0].name || '图片',
              extname: e.tempFiles[0].extname || 'jpg',
              url: e.tempFiles[0].url,
              size: e.tempFiles[0].size || 0,
              type: 'image',
              progress: 100,
              status: 'success'
            }]
          }
        }
      },
      onImageDelete(e) {
        console.log('删除文件：', e)
        this.formData.image = ''
      },
      // 自定义上传方法（可选，如果uni-file-picker不能满足需求）
      async customUpload(file) {
        try {
          const result = await uniCloud.uploadFile({
            filePath: file.path,
            cloudPath: `food_images/${Date.now()}-${file.name}`,
            cloudPathAsRealPath: true,  // 特别针对阿里云
            onUploadProgress: (progressEvent) => {
              const percentCompleted = Math.round(
                (progressEvent.loaded * 100) / progressEvent.total
              );
              console.log('上传进度：', percentCompleted);
            }
          });
          
          return result;
        } catch (e) {
          console.error('上传失败：', e);
          throw e;
        }
      },
      async detectCloudProvider() {
        try {
          const testId = 'cloud://test-id';
          const result = await uniCloud.getTempFileURL({
            fileList: [testId]
          });
          
          if (result.fileList && result.fileList[0]) {
            const errMsg = result.fileList[0].errMsg || '';
            if (errMsg.includes('aliyun')) {
              this.cloudProvider = 'aliyun';
              console.log('检测到阿里云环境');
            } else {
              this.cloudProvider = 'alipay';
              console.log('检测到支付宝云环境');
            }
          }
        } catch (e) {
          console.error('云环境检测失败，默认使用支付宝云处理方式', e);
          this.cloudProvider = 'alipay';
        }
      }
    }
  }
</script>
